package net.esj.basic.plugins.spring.support;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ResourceBundleMessageSource;

public class PlatformResourceBundleMessageSource extends
		ResourceBundleMessageSource implements AutoExpandMessageSource{

	@Override
	public String getMessage(String bundleName, String code, Object[] args,
			String defaultMessage, Locale locale) {
		ResourceBundle rb = getResourceBundle(bundleName, locale);
		if(rb!=null){
			MessageFormat messageFormat = getMessageFormat(rb, code, locale);
			if(messageFormat!=null){
				synchronized (messageFormat) {
					return messageFormat.format(args);
				}
			}
		}
		String msg = getMessage(code, args, locale);
		if(msg==null){
			msg = renderDefaultMessage(defaultMessage, args, locale);
		}
		return msg;
	}

	@Override
	public String getMessage(String bundleName, String code, Object[] args,
			Locale locale) throws NoSuchMessageException {
		ResourceBundle rb = getResourceBundle(bundleName, locale);
		if(rb!=null){
			MessageFormat messageFormat = getMessageFormat(rb, code, locale);
			if(messageFormat!=null){
				synchronized (messageFormat) {
					return messageFormat.format(args);
				}
			}
		}
		String msg = getMessage(code, args, locale);
		if(msg==null){
			msg = getDefaultMessage(code);
		}
		return msg;
	}
}
